import type { TableState } from '@/components/common/ProTable/interface'

/**
 * @description useTable 接收参数
 * @param {Function} api 获取表格数据 api 方法 (必传)
 * @param {Object} extraParam 额外参数 (非必传，默认为{})
 * @param {Boolean} isPagination 是否有分页 (非必传，默认为true)
 * @param {Function} dataFormatter 返回数据格式化方法 (非必传)
 */
export const useTable = (
  api?: (params: any) => Promise<any>,
  extraParam: object = {},
  isPagination: boolean = true,
  dataFormatter?: (data: any, currentTime: string) => any
) => {
  const state = reactive<TableState>({
    tableData: [],
    pageParam: {
      pageNo: 1,
      pageSize: 30,
      total: 0
    },
    searchParam: {},
    searchInitParam: {},
    actualParam: {},
    loading: false,
    searchDrawerVisible: false
  })

  /** 获取表格数据 */
  const getTableList = async () => {
    if (!api) return
    try {
      state.loading = true
      Object.assign(state.actualParam, extraParam, isPagination ? state.pageParam : {})
      let { data, currentTime } = await api({ ...state.searchInitParam, ...state.actualParam })
      if (dataFormatter) {
        const _data = await dataFormatter(isPagination ? data.data : data, currentTime)
        isPagination ? (data.data = _data) : (data = _data)
      }
      state.tableData = isPagination ? data.data : data
      if (isPagination) state.pageParam.total = data.total
    } catch (err) {
      state.tableData = []
      state.pageParam.total = 0
    } finally {
      state.loading = false
    }
  }

  /**
   * @description 更新查询参数
   * @return void
   * */
  const updatedTotalParam = () => {
    state.actualParam = {}
    // 处理查询参数，可以给查询参数加自定义前缀操作
    let nowSearchParam: TableState['searchParam'] = {}
    // 防止手动清空输入框携带参数（这里可以自定义查询参数前缀）
    for (let key in state.searchParam) {
      // 某些情况下参数为 false/0 也应该携带参数
      if (
        state.searchParam[key] ||
        state.searchParam[key] === false ||
        state.searchParam[key] === 0
      ) {
        nowSearchParam[key] = state.searchParam[key]
      }
    }
    Object.assign(state.actualParam, nowSearchParam)
  }
  /** 表格数据查询 */
  const search = () => {
    state.pageParam.pageNo = 1
    Object.assign(state.actualParam, state.searchParam)
    getTableList()
    state.searchDrawerVisible = false
  }

  /** 表格数据重置 */
  const reset = () => {
    state.pageParam.pageNo = 1
    state.searchParam = { ...state.searchInitParam } //重置搜索表单视图数据
    updatedTotalParam()
    getTableList()
    state.searchDrawerVisible = false
  }

  /** 每页条数改变 */
  const handleSizeChange = (val: number) => {
    state.pageParam.pageNo = 1
    state.pageParam.pageSize = val
    getTableList()
  }

  /** 当前页改变 */
  const handleCurrentChange = (val: number) => {
    state.pageParam.pageNo = val
    getTableList()
  }

  return {
    ...toRefs(state),
    getTableList,
    search,
    reset,
    handleSizeChange,
    handleCurrentChange
  }
}
